/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import entities.Account;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author QUY_THI
 */
@ManagedBean
@ViewScoped
public class AccountDepositBean {

    @EJB
    private AccountDepositLocal accountDeposit;
    @EJB
    private AccountDetailLocal accountDetail;
    private String amount;
    private String accountCode;
    private Account account;

    public Account getAccount() {
        return accountDetail.accountDetail(accountCode);
    }

    public void setAccount(Account account) {
        this.account = account;
    }

    public String getAccountCode() {
        return accountCode;
    }

    public void setAccountCode(String accountCode) {
        this.accountCode = accountCode;
    }

    public String getAmount() {
        return amount;
    }

    public void setAmount(String amount) {
        this.amount = amount;
    }

    /** Creates a new instance of AccountDepositBean */
    public AccountDepositBean() {
    }

    public String deposit() {
        if (accountCode != null) {
            double d = Double.parseDouble(amount);
            if (d % 50000 != 0) {
                FacesMessage msg = new FacesMessage("Error", "Amount must multiples of 50000 ");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return "";
            } else {
                BigDecimal money = BigDecimal.valueOf(d);
                account = accountDetail.accountDetail(accountCode);
                boolean accountDeposit1 = accountDeposit.accountDeposit(account, money);
                if (!accountDeposit1) {
                    FacesMessage msg = new FacesMessage("Error", "Error try again later !! ");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return "";
                }
                 FacesMessage msg = new FacesMessage("success", "transaction successfull !! ");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                return "home.xhtml?faces-redirect=true";
            }
        } else {
            return "home.xhtml?faces-redirect=true";
        }
    }

    public String getAutoRedirect() throws IOException {
        if (accountCode == null || accountCode.equals("")) {
            FacesContext context = FacesContext.getCurrentInstance();
            ((HttpServletResponse) context.getExternalContext().getResponse()).sendRedirect("../faces/home.xhtml");
        }
        return "";
    }
}
